﻿using AspNetCore.Practice.Domain.Entities;
using AspNetCore.Practice.Domain.IRepositories;
using AspNetCore.Practice.Domain.Mediators;
using SD.Infrastructure.Constants;
using SD.Infrastructure.RepositoryBase;

namespace AspNetCore.Practice.Repository.Base
{
    /// <summary>
    /// 数据初始化器实现
    /// </summary>
    public class DataInitializer : IDataInitializer
    {
        #region # 字段及依赖注入构造器

        /// <summary>
        /// 仓储中介者
        /// </summary>
        private readonly RepositoryMediator _repMediator;

        /// <summary>
        /// 单元事务
        /// </summary>
        private readonly IUnitOfWorkPractice _unitOfWork;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        /// <param name="repMediator">仓储中介者</param>
        /// <param name="unitOfWork">单元事务</param>
        public DataInitializer(RepositoryMediator repMediator, IUnitOfWorkPractice unitOfWork)
        {
            this._repMediator = repMediator;
            this._unitOfWork = unitOfWork;
        }

        #endregion

        //Implements

        #region # 初始化基础数据 —— void Initialize()
        /// <summary>
        /// 初始化基础数据
        /// </summary>
        public void Initialize()
        {
            this.InitAdmin();
            this.InitInfoSystems();
        }
        #endregion


        //Private

        #region # 初始化超级管理员 —— void InitAdmin()
        /// <summary>
        /// 初始化超级管理员
        /// </summary>
        private void InitAdmin()
        {
            if (!this._repMediator.UserRep.Exists(CommonConstants.AdminLoginId))
            {
                User admin = new User(CommonConstants.AdminLoginId, "超级管理员", CommonConstants.InitialPassword);

                this._unitOfWork.RegisterAdd(admin);
                this._unitOfWork.Commit();
            }
        }
        #endregion

        #region # 初始化信息系统 —— void InitInfoSystems()
        /// <summary>
        /// 初始化信息系统
        /// </summary>
        private void InitInfoSystems()
        {
            if (this._repMediator.InfoSystemRep.Count() == 0)
            {
                InfoSystem authSystem = new InfoSystem("00", "身份认证", "identity", ApplicationType.Web);

                this._unitOfWork.RegisterAdd(authSystem);
                this._unitOfWork.Commit();
            }
        }
        #endregion
    }
}
